﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Configuration;

namespace WindowsFormsWsConsumer
{
    public partial class FrmOdataConsumer : Form
    {
        public FrmOdataConsumer()
        {
            InitializeComponent();
        }

        string _ServerAddress = "";

        private void FrmOdataConsumer_Load(object sender, EventArgs e)
        {
            try
            {
                _ServerAddress = ConfigurationSettings.AppSettings["ServerAddress"];
            }
            catch
            {
                MessageBox.Show("Cannot read ServerAddress from config file");
            }
        }

        public void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = wr.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string fileName = Path.GetFileName(file);
            string header = string.Format(headerTemplate, paramName, fileName, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
        }

        private void btnUploadImage_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog saveFileDialog1 = new OpenFileDialog();
                saveFileDialog1.Filter = "JPeg Image|*.*|Bitmap Image|*.bmp|Gif Image|*.gif";
                saveFileDialog1.Title = "Save an Image File";
                saveFileDialog1.ShowDialog();

                if (saveFileDialog1.FileName != "")
                {
                    NameValueCollection nvc = new NameValueCollection();
                    nvc.Add("longitude",  txtLongitude.Text.Trim());
                    nvc.Add("latitude", txtLatitude.Text.Trim());

                    String fileName = Path.GetFileName(saveFileDialog1.FileName);
                    HttpUploadFile(string.Format("http://{0}/SocialPhotosDebug/Upload.ashx", _ServerAddress), saveFileDialog1.FileName, "files[]", "image/jpeg", nvc);
                }
            }
            catch (Exception ex)
            {
            }
        }
        
        private void btnComment_Click(object sender, EventArgs e)
        {
            try
            {
                string dataToPost = string.Format("userID={0}&photoId={1}&comment={2}", cmbUser.Text, cmbPhoto.Text, txtComment.Text);
                byte[] buffer = Encoding.UTF8.GetBytes(dataToPost);

                string url = string.Format(" http://{0}/SocialPhotos/Comment.ashx", _ServerAddress);

                HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
                WebReq.Method = "POST";
                WebReq.KeepAlive = true;
                WebReq.ContentType = "application/x-www-form-urlencoded";
                WebReq.ContentLength = buffer.Length;

                Stream PostData = WebReq.GetRequestStream();
                PostData.Write(buffer, 0, buffer.Length);
                PostData.Close();

                HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
                Console.WriteLine(WebResp.StatusCode);
                Console.WriteLine(WebResp.Server);

                Stream Answer = WebResp.GetResponseStream();
                StreamReader _Answer = new StreamReader(Answer);
                Console.WriteLine(_Answer.ReadToEnd());
            }
            catch (Exception ex)
            {
            }
        }

    

        private void btnGet_Click(object sender, EventArgs e)
        {
            try
            {
                webBrowser1.Url = new Uri(txtUrl.Text);
            }
            catch (Exception ex)
            {
            }
        }
    }
}
